﻿using CRM.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using CRM.Services.Customer;
using CRM.Extensions;

namespace CRM.Controllers.Customer
{
    using CustomerModel = CRM.Models.Customer;

    [Route("client/[controller]")]
    public class ImportController : BaseController
    {

        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;
        private readonly CustomerService _customerService;

        private readonly int CustomerIsExist = 1;
        private readonly int CustomerImportParamsFail = 2;
        private readonly int CustomerEmailIsFail = 3;
        private readonly int CustomerImportFail = 4;
        private readonly int CustomerMobileIsFail = 5;
        private readonly int ImportInitIsFail = 6;
        private readonly int BlockIsNotExist = 7;


        public ImportController(MyDbContext dbContext, UserManager<User> userManager, CustomerService customerService)
        {
            _dbContext = dbContext;
            _userManager = userManager;
            _customerService = customerService;
        }

        [HttpPost(nameof(Init))]
        public async Task<ResultStruct> Init()
        {
            var user = await _userManager.GetUserAsync(User);
            var BlockName = DateTime.Now.ToString() + "客户端导入";


            var Block = new CustomerCompany()
            {
                Name = BlockName,
                NameHash = BlockName.GetFixedHashCode(),
                From = CustomerCompany.FromType.Other,
                IsExistPrivate = CustomerCompany.IsExistPrivateType.NO,
                IsExistMy = CustomerCompany.IsExistMyType.Yes,
            };

            var Id = await _customerService.CreateBlockReturnId(Block);
            if(Id < 0)
            {
                return Fail(new object(), "初始化失败", ImportInitIsFail);
            }

            return Complete(new { BlockID = Id }, "获取成功");

        }

        [HttpPost(nameof(Customer))]
        public async Task<ResultStruct> Customer(CustomerModel customer)
        {

            var CustomerCompanyModel = _customerService.CustomerCompanyCondition();

            var BlockId = customer.BlockId;

            var row = await CustomerCompanyModel
                .Where(m => m.Id == BlockId)
                .FirstOrDefaultAsync();
            if (row == null)
            {
                return Fail(new object(), "数据不存在", BlockIsNotExist);
            }

            var user = _customerService.CurrentUser;


            if (user.Company.IsRepetitionAllowed == Company.IsRepetitionAllowedType.ENABLE)
            {
                var repeat = await _dbContext.Customer.Where(m => m.Email == customer.Email && m.OemId == user.OemId)
                               .FirstOrDefaultAsync();

                if (repeat != null)
                {

                    return Fail(new object(), $"该客户已存在【{customer.Email}】", CustomerIsExist);
                }
            }


            if (string.IsNullOrEmpty(customer.Name))
            {
                return Fail(new object(), "参数丢失: Name", CustomerImportParamsFail);
            }
             
            if (!string.IsNullOrEmpty(customer.Mobile) && !Helper.CheckPhone(customer.Mobile))
            {
                return Fail(new object(), "手机号非法", CustomerMobileIsFail);
            }

            if (string.IsNullOrEmpty(customer.Email))
            {
                return Fail(new object(), "参数丢失: Email", CustomerImportParamsFail);
            }

            if (Helper.CheckEmail(customer.Email))
            {
                return Fail(new object(), "邮箱非法", CustomerEmailIsFail);
            }

            customer.BlockId = BlockId;

            var res = await _customerService.Create(customer);
            return res ? Complete(new object(), "导入成功") : Fail(new object(), _customerService.Error, CustomerImportFail);

        }

        protected ResultStruct Complete(object data = null, string message = "成功")
        {
            data = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return FormatResult(data, message, 1000);
        }

        protected ResultStruct Fail(object data = null, string message = "失败", int code = 1001)
        {
            var Base = 10000;
            data = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return FormatResult(data, message, Base + code);
        }

        private ResultStruct FormatResult(object data, string message, int code)
        {

            return new() { Data = data, Message = message, Code = code };
        }

    }
}
